<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'
import { queryBattery } from '@/api/home'
import { queryBoxDetection, queryElectricCabinet } from '@/api/batteryswap'
import { queryChargingStation, queryChargingStationDetection } from '@/api/chargebattery'
import { ElTableV2, ElAutoResizer } from 'element-plus'
import { getToken } from '@/utils/cache/cookies'
import { ElLoading } from 'element-plus'
import { basicHomeData, basicMapData, CabinetType, ChargeCabinetType, TableType } from '@/types'
import { queryBatteryTotalDetection } from '@/api/map'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading.mjs'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import DataTitle from '@/components/basic/DataTitle.vue'
import DataItem from '@/components/basic/DataItem.vue'
import LeftTitle from '@/components/basic/LeftTitle.vue'
import RightTitle from '@/components/basic/RightTitle.vue'
import Map3D from '@/components/core/Map3D.vue'
import BorderBox1 from '@/components/basic/BorderBox1.vue'
import imgSrc from '@/assets/images/pie-bg.png'
import { Alignment } from 'element-plus/es/components/table-v2/src/constants.mjs'
import { useUserStore } from '@/store/modules/user'
const Map3DRef = ref<InstanceType<typeof Map3D> | null>(null)
/** 获取首页数据 */
const data = ref<any>(null)
const timer = ref<any>(0)
const { getType, setType } = useUserStore()
/** 电池数据 */
const MapData = ref<basicMapData[]>([])
const batteryTotal = ref<number>(0)
const boxTotal = ref<number>(0)
const chargingStationTotal = ref<number>(0)
/** 左中数据源 */
const LeftMiddleData = ref<basicHomeData<any> | null>(null)
/** 电池异常 */
const RightMiddleData = ref<basicHomeData<string[][]> | null>(null)
/** 右上数据 */
const RightTopData = ref<basicHomeData<string[][]> | null>(null)
/** 左下数据表格 */
const LeftBottomData = ref<basicHomeData<any> | null>(null)
/** 右下表格 */
const RightBottomData = ref<basicHomeData<any> | null>(null)
/** 左上数据 */
const LeftTopData = ref<basicHomeData<any> | null>(null)
/** loading */
const loadingService = ref<LoadingInstance>()
/** 取消定时器 */
const handleStopInterval = () => {
  if (timer.value) clearTimeout(timer.value)
}
/** 图表数据 */
const color: string[] = ['#00B0FF', '#47FFEC', '#FFA12E']
/** 左中图表 */
const LeftMiddleCharts = shallowRef<echarts.ECharts | null>(null)
/** 右上图表 */
const RightTopCharts = shallowRef<echarts.ECharts | null>(null)
/** 右中图表 */
const RightMiddleCharts = shallowRef<echarts.ECharts | null>(null)

const LeftBottomTableCol = ref<TableType[]>([])
const RightBottomTableCol = ref<TableType[]>([])
/** 改变地图数据的电池类型 */
const handleChangeMapData = async (t: string) => {
  loadingService.value = ElLoading.service({
    target: '.app-container',
    text: '加载中',
    fullscreen: false,
    customClass: 'full-screen-loading',
    svgViewBox: ' 0 0 65 65',
  })
  switch (getType()) {
    case '电柜总数':
      getBatteryTypeData(t)
      break
    case '换电柜总数':
      getBatterySwapTypeData(t)
      break
    default:
      getChargeBatteryTypeData(t)
      break
  }
}
const getBatteryTypeData = async (type: string) => {
  try {
    const res = await queryBatteryTotalDetection({
      token: getToken() ?? '',
      channel: 'Service',
      type: type,
    })
    if (res.resultCode === 0) {
      handleStopInterval()
      Map3DRef.value?.FirstLoad(res.resultData, '电池总数')
    }
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
}
const getBatterySwapTypeData = async (type: string) => {
  try {
    const res = await queryBoxDetection({
      token: getToken() ?? '',
      channel: 'Service',
      type: type as CabinetType,
    })
    if (res.resultCode === 0) {
      handleStopInterval()
      Map3DRef.value?.FirstLoad(res.resultData, '换电柜总数')
    }
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
}
const getChargeBatteryTypeData = async (type: string) => {
  try {
    const res = await queryChargingStationDetection({
      token: getToken() ?? '',
      channel: 'Service',
      type: type as ChargeCabinetType,
    })
    if (res.resultCode === 0) {
      handleStopInterval()
      Map3DRef.value?.FirstLoad(res.resultData, '充电柜总数')
    }
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
}
const getBatteryData = async () => {
  handleStopInterval()
  setType('电柜总数')
  loadingService.value = ElLoading.service({
    target: '.app-container',
    text: '加载中',
    fullscreen: false,
    customClass: 'full-screen-loading',
    svgViewBox: ' 0 0 65 65',
  })
  try {
    const res = await queryBattery({
      token: getToken() ?? '',
      channel: 'Service',
    })
    if (res.resultCode === 0) {
      data.value = res.resultData
      batteryTotal.value = res.resultData.batteryTotal
      boxTotal.value = res.resultData.boxTotal
      chargingStationTotal.value = res.resultData.chargingStationTotal
      LeftTopData.value = res.resultData.detection
      LeftMiddleData.value = res.resultData.proportion
      LeftBottomData.value = res.resultData.record
      RightMiddleData.value = res.resultData.getTrend
      RightTopData.value = res.resultData.getRealtimeDataset
      RightBottomData.value = res.resultData.pushData
      MapData.value = res.resultData.batteryDataDTOList
      Map3DRef.value?.FirstLoad(MapData.value, '电池总数')
      setBatteryChartsData()
      Map3DRef.value?.batteryTotalClick()
    }
    LeftBottomTableCol.value = changeLeftBottomTableCol('电池总数')
    RightBottomTableCol.value = changeRightBottomTableCol('电池总数')
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
  timer.value = setTimeout(() => {
    getBatteryData()
  }, 60000)
}
const getBoxData = async () => {
  handleStopInterval()
  setType('换电柜总数')
  loadingService.value = ElLoading.service({
    target: '.app-container',
    text: '加载中',
    fullscreen: false,
    customClass: 'full-screen-loading',
    svgViewBox: ' 0 0 65 65',
  })
  try {
    const res = await queryElectricCabinet({
      token: getToken() ?? '',
      channel: 'Service',
    })
    if (res.resultCode === 0) {
      LeftMiddleCharts.value?.clear()
      RightTopCharts.value?.clear()
      RightMiddleCharts.value?.clear()
      data.value = res.resultData
      batteryTotal.value = res.resultData.batteryTotal
      boxTotal.value = res.resultData.boxTotal
      chargingStationTotal.value = res.resultData.chargingStationTotal
      LeftTopData.value = res.resultData.detection
      LeftMiddleData.value = res.resultData.proportion
      LeftBottomData.value = res.resultData.record
      RightMiddleData.value = res.resultData.getTrend
      RightTopData.value = res.resultData.getRealtimeDataset
      RightBottomData.value = res.resultData.pushData
      MapData.value = res.resultData.boxDataList
      Map3DRef.value?.FirstLoad(MapData.value, '换电柜总数')
      setBatterySwapChartsData()
    }
    LeftBottomTableCol.value = changeLeftBottomTableCol('换电柜总数')
    RightBottomTableCol.value = changeRightBottomTableCol('换电柜总数')
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
  timer.value = setTimeout(() => {
    getBoxData()
  }, 60000)
}
const getChargeBatteryData = async () => {
  handleStopInterval()
  setType('充电柜总数')
  loadingService.value = ElLoading.service({
    target: '.app-container',
    text: '加载中',
    fullscreen: false,
    customClass: 'full-screen-loading',
    svgViewBox: ' 0 0 65 65',
  })
  try {
    const res = await queryChargingStation({
      token: getToken() ?? '',
      channel: 'Service',
    })
    if (res.resultCode === 0) {
      LeftMiddleCharts.value?.clear()
      RightTopCharts.value?.clear()
      RightMiddleCharts.value?.clear()
      data.value = res.resultData
      batteryTotal.value = res.resultData.batteryTotal
      boxTotal.value = res.resultData.boxTotal
      chargingStationTotal.value = res.resultData.chargingStationTotal
      LeftTopData.value = res.resultData.detection
      LeftMiddleData.value = res.resultData.proportion
      LeftBottomData.value = res.resultData.record
      RightMiddleData.value = res.resultData.getTrend
      RightTopData.value = res.resultData.getRealtimeDataset
      RightBottomData.value = res.resultData.pushData
      MapData.value = res.resultData.boxDataList
      Map3DRef.value?.FirstLoad(MapData.value, '充电柜总数')
      setChargeBatteryChartsData()
    }
    LeftBottomTableCol.value = changeLeftBottomTableCol('充电柜总数')
    RightBottomTableCol.value = changeRightBottomTableCol('充电柜总数')
    loadingService.value?.close()
  } catch (error) {
    console.error(error)
    loadingService.value?.close()
  }
  timer.value = setTimeout(() => {
    getChargeBatteryData()
  }, 60000)
}
const switchData = () => {
  switch (getType()) {
    case '电柜总数':
      getBatteryData()
      break
    case '换电柜总数':
      getBoxData()
      break
    default:
      getChargeBatteryData()
      break
  }
}
const changeLeftBottomTableCol = (type: string) => {
  switch (type) {
    case '电池总数':
      return [
        {
          key: 'battery-total-storeName',
          dataKey: 'storeName',
          title: '站点名称',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-chargeCount',
          dataKey: 'chargeCount',
          title: '充电数量',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-abnormalCount',
          dataKey: 'abnormalCount',
          title: '异常数量',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-dataTime',
          dataKey: 'dataTime',
          title: '数据时间',
          width: 258,
          align: Alignment.CENTER,
        },
      ]
    case '换电柜总数':
      return [
        {
          key: 'batteryswap-total-deviceCode',
          dataKey: 'deviceCode',
          title: '电柜编号',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'batteryswap-total-category',
          dataKey: 'category',
          title: '故障内容',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'batteryswap-total-faultDescription',
          dataKey: 'faultDescription',
          title: '内容详情',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'batteryswap-total-updatedTime',
          dataKey: 'updatedTime',
          title: '推送时间',
          width: 200,
          align: Alignment.CENTER,
        },
      ]
    case '充电柜总数':
      return [
        {
          key: 'chargebattery-total-deviceCode',
          dataKey: 'deviceCode',
          title: '电柜编号',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'chargebattery-total-category',
          dataKey: 'category',
          title: '故障类型',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'chargebattery-total-updatedTime',
          dataKey: 'updatedTime',
          title: '故障时间',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'chargebattery-total-state',
          dataKey: 'state',
          title: '处理状态',
          width: 200,
          align: Alignment.CENTER,
        },
      ]
    default:
      return []
  }
}
const changeRightBottomTableCol = (type: string) => {
  switch (type) {
    case '电池总数':
      return [
        {
          key: 'battery-total-batteryLockId',
          dataKey: 'batteryLockId',
          title: '电池编号',
          width: 150,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-alarmContent',
          dataKey: 'alarmContent',
          title: '告警内容',
          width: 150,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-pushMode',
          dataKey: 'pushMode',
          title: '推送方式',
          width: 150,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-createdTime',
          dataKey: 'createdTime',
          title: '推送时间',
          width: 250,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-total-receiverName',
          dataKey: 'receiverName',
          title: '接收人',
          width: 150,
          align: Alignment.CENTER,
        },
      ]
    case '换电柜总数':
      return [
        {
          key: 'battery-swap-boxId',
          dataKey: 'boxId',
          title: '电柜编号',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-swap-category',
          dataKey: 'category',
          title: '告警内容',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-swap-remark',
          dataKey: 'remark',
          title: '内容详情',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'battery-swap-createdTime',
          dataKey: 'createdTime',
          title: '推送时间',
          width: 200,
          align: Alignment.CENTER,
        },
      ]
    case '充电柜总数':
      return [
        {
          key: 'charge-battery-boxId',
          dataKey: 'boxId',
          title: '电柜编号',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'charge-battery-category',
          dataKey: 'category',
          title: '告警内容',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'charge-battery-remark',
          dataKey: 'remark',
          title: '内容详情',
          width: 200,
          align: Alignment.CENTER,
        },
        {
          key: 'charge-battery-createdTime',
          dataKey: 'createdTime',
          title: '推送时间',
          width: 200,
          align: Alignment.CENTER,
        },
      ]
    default:
      return []
  }
}
/** 图表初始化 */
const initCharts = () => {
  if (LeftMiddleCharts.value !== null && LeftMiddleCharts.value !== undefined) {
    LeftMiddleCharts.value.dispose()
  }
  if (RightTopCharts.value !== null && RightTopCharts.value !== undefined) {
    RightTopCharts.value.dispose()
  }
  if (RightMiddleCharts.value !== null && RightMiddleCharts.value !== undefined) {
    RightMiddleCharts.value.dispose()
  }
  const chartDom = document.getElementById('state-fault-per-chart')
  const cycleChartDom = document.getElementById('cycle-count-chart')
  const batteryAbnormalChartDom = document.getElementById('battery-abnormal-trend-chart')
  LeftMiddleCharts.value = echarts.init(chartDom)
  RightTopCharts.value = echarts.init(cycleChartDom)
  RightMiddleCharts.value = echarts.init(batteryAbnormalChartDom)
  window.onresize = () => {
    LeftMiddleCharts.value?.resize()
    RightTopCharts.value?.resize()
    RightMiddleCharts.value?.resize()
  }
}
/** 图表数据配置 */
const setBatteryChartsData = () => {
  const StateFaultChartsOptions: echarts.EChartsCoreOption = {
    name: '站点异常检测',
    series: {
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['35%', '60%'],
      labelLine: {
        show: true,
        length: 50,
        length2: 50,
        lineStyle: {
          width: 2,
        },
      },
      data: LeftMiddleData.value?.value,
      label: {
        alignTo: 'labelLine',
        position: 'outside',
        fontSize: 16,
        formatter: ['{bx|{b}}', '{dx|{d}%}'].join('\n'),
        minAngle: 5, //最小的扇区角度（0 ~ 360），用于防止某个值过小导致扇区太小影响交互
        avoidLabelOverlap: true, //是否启用防止标签重叠策略
        rich: {
          bx: {
            fontSize: 20,
            fontWeight: 500,
            color: '#FFF',
            padding: [10, 10, 10, 10],
          },
          dx: {
            fontSize: 30,
            fontWeight: 600,
            color: '#FFF',
            padding: [10, 10, 10, 10],
          },
        },
      },
    },
    graphic: {
      elements: [
        {
          type: 'image',
          z: 6,
          style: {
            image: imgSrc,
            width: 140,
            height: 140,
            shadowBlur: 0,
            shadowColor: '#000',
            shadowOffsetX: '1',
            shadowOffsetY: '1',
          },
          left: '42%',
          top: '37%',
        },
      ],
    },
    color: color,
    tooltip: {
      trigger: 'item',
      textStyle: {
        fontSize: 28,
      },
    },
  }
  const CycleCountChartsOptions: echarts.EChartsCoreOption = {
    series: [
      {
        name: '循环数量',
        type: 'bar',
        encode: {
          x: '区间',
          y: '循环数量',
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#00E6FF', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#45AAFF', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
        barWidth: 20,
      },
      {
        name: '占比率',
        type: 'line',
        encode: {
          x: '区间',
          y: '占比率',
        },
        yAxisIndex: 1,
      },
    ],
    xAxis: {
      type: 'category',
      axisLabel: {
        fontSize: 16,
        verticalAlign: 'middle',
        color: '#FFF',
        margin: 15,
        interval: 0,
      },
      axisLine: {
        lineStyle: {
          color: '#45AAFF',
          width: 2,
          opacity: 0.3,
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '循环数量(个)',
        position: 'left',
        axisLabel: {
          fontSize: 16,
          verticalAlign: 'middle',
          color: '#75787E',
        },
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        lineStyle: {
          show: true,
          // 使用深浅的间隔色
          color: '#45AAFF',
          opacity: 0.03,
        },
        splitLine: {
          show: false,
        },
      },
      {
        type: 'value',
        name: '占比率 (%)',
        position: 'right',
        axisLabel: {
          show: true,
          formatter: '{value}%',
          fontSize: 16,
          verticalAlign: 'middle',
          color: '#75787E',
        },
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        lineStyle: {
          show: true,
          // 使用深浅的间隔色
          color: '#45AAFF',
          opacity: 0.03,
        },
        splitLine: {
          show: false,
        },
      },
    ],
    tooltip: {
      trigger: 'item',
      backgroundColor: '#000',
      borderColor: 'transparent',
      enterable: true,
      textStyle: {
        fontSize: 26,
      },
      formatter: (params: any) => {
        return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
               <div>
             ${params.marker} ${params.dimensionNames[2]}: ${params.value[2]}%
              </div>
           </div>`
      },
    },
    dataset: {
      source: RightTopData.value?.value,
      dimensions: ['区间', '循环数量', '占比率'],
    },
  }
  const batteryAbnormalChartOptions: echarts.EChartsCoreOption = {
    series: [
      {
        type: 'line',
        color: '#47FFEC',
      },
      {
        type: 'line',
        color: '#FFCB31',
      },
    ],
    xAxis: {
      type: 'category',
      nameTextStyle: {
        fontSize: 16,
        color: '#75787E',
      },
      axisLabel: {
        color: '#FFF',
        fontSize: 20,
        formatter: function (value: any) {
          return dayjs(value).format('MM/DD')
        },
        interval: 0,
        margin: 10,
      },
      axisLine: {
        lineStyle: {
          color: '#45AAFF',
          width: 2,
          opacity: 0.3,
        },
      },
      axisTick: {
        show: false,
      },
    },
    legend: {
      right: 10,
      top: 10,
      textStyle: {
        fontSize: 20,
        color: '#FFF',
        itemWidth: 50,
      },
    },
    yAxis: {
      show: true,
      axisLabel: {
        fontSize: 16,
        color: '#75787E',
        verticalAlign: 'middle',
      },
      nameTextStyle: {
        fontSize: 16,
        color: '#75787E',
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#45AAFF',
          width: 2,
          opacity: 0.3,
        },
      },
      axisTick: {
        alignWithLabel: true,
      },
      lineStyle: {
        show: true,
        // 使用深浅的间隔色
        color: '#45AAFF',
        opacity: 0.03,
      },
      splitLine: {
        show: false,
      },
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: '#000',
      borderColor: 'transparent',
      enterable: true,
      textStyle: {
        fontSize: 26,
      },
      formatter: (params: any) => {
        return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
               <div>
             ${params.marker} ${params.dimensionNames[2]}: ${params.value[2]}
              </div>
           </div>`
      },
    },
    dataset: {
      source: RightMiddleData.value?.value,
    },
  }
  LeftMiddleCharts.value?.setOption(StateFaultChartsOptions)
  RightTopCharts.value?.setOption(CycleCountChartsOptions)
  RightMiddleCharts.value?.setOption(batteryAbnormalChartOptions)
}
const setBatterySwapChartsData = () => {
  try {
    const BatteryPercentageChartOption: echarts.EChartsCoreOption = {
      name: '电池占比',
      series: {
        type: 'pie',
        center: ['50%', '50%'],
        radius: ['35%', '60%'],
        labelLine: {
          show: true,
          length: 50,
          length2: 50,
          lineStyle: {
            width: 2,
          },
        },
        data: LeftMiddleData.value?.value,
        label: {
          alignTo: 'labelLine',
          position: 'outside',
          fontSize: 16,
          formatter: ['{bx|{b}}', '{dx|{d}%}'].join('\n'),
          minAngle: 5, //最小的扇区角度（0 ~ 360），用于防止某个值过小导致扇区太小影响交互
          avoidLabelOverlap: true, //是否启用防止标签重叠策略
          rich: {
            bx: {
              fontSize: 20,
              fontWeight: 500,
              color: '#FFF',
              padding: [10, 10, 10, 10],
            },
            dx: {
              fontSize: 30,
              fontWeight: 600,
              color: '#FFF',
              padding: [10, 10, 10, 10],
            },
          },
        },
      },
      graphic: {
        elements: [
          {
            type: 'image',
            z: 6,
            style: {
              image: imgSrc,
              width: 140,
              height: 140,
              shadowBlur: 0,
              shadowColor: '#000',
              shadowOffsetX: '1',
              shadowOffsetY: '1',
            },
            left: '42%',
            top: '37%',
          },
        ],
      },
      color: color,
      tooltip: {
        trigger: 'item',
        textStyle: {
          fontSize: 28,
        },
      },
    }
    const CycleCountChartsOptions: echarts.EChartsCoreOption = {
      series: [
        {
          name: '换电次数统计',
          type: 'bar',
          encode: {
            x: '区间',
            y: '电柜数',
          },
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#00E6FF', // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#45AAFF', // 100% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          },
          barWidth: 20,
        },
      ],
      xAxis: {
        type: 'category',
        axisLabel: {
          fontSize: 16,
          verticalAlign: 'middle',
          color: '#FFF',
          margin: 15,
          interval: 0,
        },
        axisLine: {
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '电柜个数(个)',
          position: 'left',
          axisLabel: {
            fontSize: 16,
            verticalAlign: 'middle',
            color: '#75787E',
          },
          nameTextStyle: {
            fontSize: 16,
            color: '#75787E',
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#45AAFF',
              width: 2,
              opacity: 0.3,
            },
          },
          lineStyle: {
            show: true,
            // 使用深浅的间隔色
            color: '#45AAFF',
            opacity: 0.03,
          },
          splitLine: {
            show: false,
          },
        },
      ],
      tooltip: {
        trigger: 'item',
        backgroundColor: '#000',
        borderColor: 'transparent',
        enterable: true,
        textStyle: {
          fontSize: 26,
        },
        formatter: (params: any) => {
          return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
               <div>
             ${params.marker} ${params.dimensionNames[2]}: ${params.value[2]}%
              </div>
           </div>`
        },
      },
      dataset: {
        source: RightTopData.value?.value,
        dimensions: ['区间', '电池数'],
      },
    }
    const BatterySwapTrendChartOptions: echarts.EChartsCoreOption = {
      series: [
        {
          type: 'line',
          color: '#45AAFF',
        },
      ],
      xAxis: {
        type: 'category',
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLabel: {
          color: '#FFF',
          fontSize: 20,
          formatter: function (value: any) {
            return dayjs(value).format('MM/DD')
          },
          interval: 0,
          margin: 10,
        },
        axisLine: {
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          show: false,
        },
      },
      legend: {
        right: 10,
        top: 10,
        textStyle: {
          fontSize: 20,
          color: '#FFF',
          itemWidth: 50,
        },
      },
      yAxis: {
        show: true,
        axisLabel: {
          fontSize: 16,
          color: '#75787E',
          verticalAlign: 'middle',
        },
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
        lineStyle: {
          show: true,
          // 使用深浅的间隔色
          color: '#45AAFF',
          opacity: 0.03,
        },
        splitLine: {
          show: false,
        },
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: '#000',
        borderColor: 'transparent',
        enterable: true,
        textStyle: {
          fontSize: 26,
        },
        formatter: (params: any) => {
          return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
           </div>`
        },
      },
      dataset: {
        source: RightMiddleData.value?.value,
      },
    }
    LeftMiddleCharts.value?.setOption(BatteryPercentageChartOption)
    RightTopCharts.value?.setOption(CycleCountChartsOptions)
    RightMiddleCharts.value?.setOption(BatterySwapTrendChartOptions)
  } catch (error) {
    console.error(error)
  }
}
const setChargeBatteryChartsData = () => {
  try {
    const option1: echarts.EChartsCoreOption = {
      name: '电柜占比',
      series: {
        type: 'pie',
        center: ['50%', '50%'],
        radius: ['35%', '60%'],
        labelLine: {
          show: true,
          length: 50,
          length2: 50,
          lineStyle: {
            width: 2,
          },
        },
        data: LeftMiddleData.value?.value,
        label: {
          alignTo: 'labelLine',
          position: 'outside',
          fontSize: 16,
          formatter: ['{bx|{b}}', '{dx|{d}%}'].join('\n'),
          minAngle: 5, //最小的扇区角度（0 ~ 360），用于防止某个值过小导致扇区太小影响交互
          avoidLabelOverlap: true, //是否启用防止标签重叠策略
          rich: {
            bx: {
              fontSize: 20,
              fontWeight: 500,
              color: '#FFF',
              padding: [10, 10, 10, 10],
            },
            dx: {
              fontSize: 30,
              fontWeight: 600,
              color: '#FFF',
              padding: [10, 10, 10, 10],
            },
          },
        },
      },
      graphic: {
        elements: [
          {
            type: 'image',
            z: 6,
            style: {
              image: imgSrc,
              width: 140,
              height: 140,
              shadowBlur: 0,
              shadowColor: '#000',
              shadowOffsetX: '1',
              shadowOffsetY: '1',
            },
            left: '42%',
            top: '37%',
          },
        ],
      },
      color: color,
      tooltip: {
        trigger: 'item',
        textStyle: {
          fontSize: 28,
        },
      },
    }
    const option2: echarts.EChartsCoreOption = {
      series: [
        {
          name: '超温次数统计',
          type: 'bar',
          encode: {
            x: '区间',
            y: '电柜数',
          },
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#00E6FF', // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#45AAFF', // 100% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          },
          barWidth: 20,
        },
      ],
      xAxis: {
        type: 'category',
        axisLabel: {
          fontSize: 16,
          verticalAlign: 'middle',
          color: '#FFF',
          margin: 15,
          interval: 0,
        },
        axisLine: {
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '电池个数(个)',
          position: 'left',
          axisLabel: {
            fontSize: 16,
            verticalAlign: 'middle',
            color: '#75787E',
          },
          nameTextStyle: {
            fontSize: 16,
            color: '#75787E',
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#45AAFF',
              width: 2,
              opacity: 0.3,
            },
          },
          lineStyle: {
            show: true,
            // 使用深浅的间隔色
            color: '#45AAFF',
            opacity: 0.03,
          },
          splitLine: {
            show: false,
          },
        },
      ],
      tooltip: {
        trigger: 'item',
        backgroundColor: '#000',
        borderColor: 'transparent',
        enterable: true,
        textStyle: {
          fontSize: 26,
        },
        formatter: (params: any) => {
          return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
           </div>`
        },
      },
      dataset: {
        source: RightTopData.value?.value,
        dimensions: ['区间', '电池数'],
      },
    }
    const option3: echarts.EChartsCoreOption = {
      series: [
        {
          type: 'line',
          color: '#45FF9F',
        },
      ],
      xAxis: {
        type: 'category',
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLabel: {
          color: '#FFF',
          fontSize: 20,
          formatter: function (value: any) {
            return dayjs(value).format('MM/DD')
          },
          interval: 0,
          margin: 10,
        },
        axisLine: {
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          show: false,
        },
      },
      legend: {
        right: 10,
        top: 10,
        textStyle: {
          fontSize: 20,
          color: '#FFF',
          itemWidth: 50,
        },
      },
      yAxis: {
        show: true,
        name: '超温次数(次)',
        axisLabel: {
          fontSize: 16,
          color: '#75787E',
          verticalAlign: 'middle',
        },
        nameTextStyle: {
          fontSize: 16,
          color: '#75787E',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#45AAFF',
            width: 2,
            opacity: 0.3,
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
        lineStyle: {
          show: true,
          // 使用深浅的间隔色
          color: '#45AAFF',
          opacity: 0.03,
        },
        splitLine: {
          show: false,
        },
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: '#000',
        borderColor: 'transparent',
        enterable: true,
        textStyle: {
          fontSize: 26,
        },
        formatter: (params: any) => {
          return `<div class="cycle-count-tooltip">
              <div>
              ${params.marker} ${params.dimensionNames[1]}: ${params.value[1]}
              </div>
           </div>`
        },
      },
      dataset: {
        source: RightMiddleData.value?.value,
      },
    }
    LeftMiddleCharts.value?.setOption(option1)
    RightTopCharts.value?.setOption(option2)
    RightMiddleCharts.value?.setOption(option3)
  } catch (error) {
    console.error(error)
  }
}
/** 页面实例暴露方法 */
const handleBackMap = () => {
  Map3DRef.value?.handleBackNode()
}
defineExpose({ handleBackMap })
/** 辅助函数 */
// watchEffect(() => {
//   console.log(type.value)
// })
/** 生命周期 */
onMounted(() => {
  switchData()
  initCharts()
})
onBeforeUnmount(() => {
  if (timer.value) {
    clearTimeout(timer.value)
  }
  LeftMiddleCharts.value?.clear()
  RightTopCharts.value?.clear()
  RightMiddleCharts.value?.clear()
})
</script>

<template>
  <div class="home-main">
    <div class="home-main__left">
      <left-title />
      <div class="bg-[#081530]" flex flex-col flex-1 mt-50 rounded-10 p-20>
        <div flex flex-col>
          <data-title :title="LeftTopData?.label" :eg-title="LeftTopData?.egLabel" />
          <div mt-20 class="batery-fault-data-container">
            <data-item
              v-for="(item, index) in LeftTopData?.value"
              :key="index"
              @click="handleChangeMapData(item.label)"
              :title="item.label"
              :value="item.value"
              cursor-pointer
            />
          </div>
        </div>
        <div flex flex-col mt-50>
          <data-title :title="LeftMiddleData?.label" :eg-title="LeftMiddleData?.egLabel" />
          <div mt-20>
            <div w-full h-500 id="state-fault-per-chart" />
          </div>
        </div>
        <div flex flex-col mt-50 flex-1>
          <data-title :title="LeftBottomData?.label" :eg-title="LeftBottomData?.egLabel" />
          <div mt-20 h-550 w-full>
            <el-auto-resizer>
              <template #default="{ height, width }">
                <el-table-v2
                  header-class="table-v2-data-header"
                  :columns="LeftBottomTableCol"
                  :data="LeftBottomData?.value ?? []"
                  :width="width"
                  :height="height"
                  :header-height="80"
                  :row-height="80"
                  :fixed="true"
                />
              </template>
            </el-auto-resizer>
          </div>
        </div>
      </div>
    </div>
    <div class="home-main__center">
      <div grid grid-cols-3 grid-rows-1 gap-x-50 class="w-[45%]">
        <border-box1
          cursor-pointer
          title="电池总数"
          :value="batteryTotal"
          @click="getBatteryData"
        />
        <border-box1 cursor-pointer title="换电柜总数" :value="boxTotal" @click="getBoxData" />
        <border-box1
          cursor-pointer
          title="充电站数"
          :value="chargingStationTotal"
          @click="getChargeBatteryData"
        />
      </div>
      <Map3D ref="Map3DRef" @clear-interval="handleStopInterval" @open-interval="switchData" />
    </div>
    <div class="home-main__right">
      <right-title />
      <div class="bg-[#081530]" flex flex-col flex-1 mt-50 rounded-10 p-20>
        <div flex flex-col>
          <data-title :title="RightTopData?.label" :eg-title="RightTopData?.egLabel" />
          <div mt-20 class="cycle-count-container">
            <div w-full h-500 id="cycle-count-chart" />
          </div>
        </div>
        <div flex flex-col mt-50>
          <data-title :title="RightMiddleData?.label" :eg-title="RightMiddleData?.egLabel" />
          <div mt-20>
            <div w-full h-400 id="battery-abnormal-trend-chart" />
          </div>
        </div>
        <div flex flex-col mt-50 flex-1>
          <data-title :title="RightBottomData?.label" :eg-title="RightBottomData?.egLabel" />
          <div mt-20 flex-1>
            <el-auto-resizer>
              <template #default="{ height, width }">
                <el-table-v2
                  header-class="table-v2-data-header"
                  :columns="RightBottomTableCol"
                  :data="RightBottomData?.value ?? []"
                  :width="width"
                  :height="height"
                  :header-height="80"
                  :row-height="80"
                  :fixed="true"
                />
              </template>
            </el-auto-resizer>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home-main {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  z-index: 10;
  &__left {
    width: 26%;
    height: 95%;
    padding: 100px 50px;
    display: flex;
    flex-direction: column;
  }
  &__right {
    width: 26%;
    height: 95%;
    padding: 100px 50px;
    display: flex;
    flex-direction: column;
    &__title {
      display: flex;
      align-items: center;
      font-size: 36px;
      line-height: 42px;
    }
  }
}
.batery-fault-data-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 20px;
}
.home-main__center {
  width: 48%;
  height: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

:deep(.battery-abnormal-warning-header) {
  background: linear-gradient(to right, #132239 0%, #1b75ff 51%, rgba(19, 34, 57, 0.22) 100%);
  font-size: 28px;
}
:deep(.cycle-count-tooltip) {
  display: flex;
  flex-direction: column;
  > div {
    display: flex;
    align-items: center;
    > span {
      margin-right: 10px !important;
    }
  }
}
:deep(.data-item-skeleton) {
  clip-path: polygon(0 0, 88% 0, 100% 40%, 100% 100%, 0 100%);
  background: linear-gradient(to right, #45aaff 0%, #000 5%, #000 63%),
    linear-gradient(135deg, rgba(0, 0, 0, 0.7) 52%, rgba(69, 170, 255, 1) 83%, #45aaff 100%);
  background-blend-mode: lighten;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  height: 120px; /* 与DataItem高度一致 */
}
</style>
